layui.define(['layer', 'table', 'element', 'form', 'jquery', 'eleTree', 'laydate','dtree','hospital'], function (exports) {
    // noinspection SpellCheckingInspection
    var layer = layui.layer //弹层
        , table = layui.table //表格
        , element = layui.element //元素操作
        , $ = layui.jquery
        , eleTree = layui.eleTree
        , form = layui.form
        , laydate = layui.laydate
        , dtree = layui.dtree
        , hospital = layui.hospital;
    var employee;
    var birthday_date = null;
    var jobData = null;
    var i=1;//为了给后台传值方便记录每条记录的number值
    var jobCount = 1;
    var rowDataInfo;
    var deptTree1;
    var deptTree2;
    var deptTree3;
    var deptTree4;
    var deptTree5;
    var deptTree99;
    var hospitalSelectInfo;
    var jobSelectInfo;
    var removeHdeIdJob = [];
    var removeEmployeeJob = { eId: '' , removeHdeIdJob :removeHdeIdJob};
    employee = {


        initEmployee:function(){
            alert(1);
            this.initEmployeeTableSearch(); //初始化员工表格 的搜索界面
            this.listenEmployeeSearchTableChooseAndClear(); //监听 用户分配员工表格搜索提交、清除按钮
            this.listenSearchEmployeeJobSelect(); //监听员工表格上方 医院下拉框选择 联动部门显示
        },

        //员工表格初始化
        init_employee_table: function () {
            employee_table_Info = table.render({
                elem: '#employee_table', //选取html表格的id
                id: 'employee_table_Id',
                response: {
                    statusCode: '200 ' //规定成功的状态码，默认：0
                }
                , url: '/manage/employee'
                , title: '员工表'
                , toolbar: '#employee_table_top'
                , page: true
                , cols: [[
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'employeeNumber', title: '工号', align: 'center', sort: true, fixed: 'left'}
                    , {field: 'employeeName', title: '姓名', align: 'center', sort: true, fixed: 'left'}
                    , {
                        field: 'sex',
                        title: '性别 ',
                        align: 'center',
                        sort: true,
                        fixed: 'left',
                        templet: function (row) {
                            return row.sex===1 ?  "女" : "男" ;
                        }
                    }
                    , {
                        field: 'age',
                        title: '年龄 ',
                        align: 'center',
                        sort: true,
                        fixed: 'left',
                    }
                    , {field: 'phone', title: '手机号', align: 'center', sort: true, fixed: 'left'}
                    , {field: 'employeeAddress', title: '地址', align: 'center', sort: true, fixed: 'left'}
                    , {field: 'jobStatus', title: '工作状态', align: 'center', sort: true, fixed: 'left',templet: function (row){
                          if (row.jobStatus!==undefined){
                              switch (row.jobStatus) {
                                  case 0:
                                      return "停职";
                                  case 1:
                                      return "在职";
                                  case 2:
                                      return "休假";
                                  case 3:
                                  case 3:
                                      return "事假";
                                  case 4:
                                      return "出差";
                                  case 5:
                                      return "病假";
                                  case 6:
                                      return "丧假";
                                  case 7:
                                      return "离职";
                                  default:
                                      return "";
                              }
                          }else {
                              return "/";
                          }
                        }}
                    ,{field: 'status', title: '状态', align:'center' , event:  'change_status',fixed: 'left',templet: function (row){
                            var status = row.status;
                            var rowData = JSON.stringify(row);
                            switch (status) {
                                case 0:
                                    return '<input type="checkbox" row-data=\''+ rowData + '\' name="status"  lay-skin="switch" lay-filter="employee_table_Switch" lay-text="启用|禁用" >';
                                case 1:
                                    return '<input type="checkbox" row-data=\''+ rowData + '\' name="status" checked lay-skin="switch" lay-filter="employee_table_Switch" lay-text="启用|禁用" > ';
                                default:
                                    return '<input type="checkbox" row-data=\''+ rowData + '\' name="status"    lay-skin="switch" lay-filter="employee_table_Switch" lay-text="启用|禁用" >' ;
                            }
                        }}
                    , {fixed: 'tool', title: '操作', width: 165, align: 'center', toolbar: '#employee_table_right'}
                ]]
            });
        },

        //监听表格行工具事件   tool是行工具条
        init_listen_table_tool() {
            table.on('tool(employee_table)', function (obj) { //注：tool 是工具条事件名，demo 是 table 原始容器的属性 lay-filter="对应的值"

                var data = null;
                data = obj.data;     //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值
                if (layEvent === 'detail_employee') {
                } else if (layEvent === 'delete_employee') {
                    //员工单行删除
                    employee.delete_employee(data);
                } else if (layEvent === 'edit_employee') {
                    //员工编辑
                    employee.init_employee_form('edit', data);
                }

            });
        },

        //监听表格头工具条事件 toolbar是头工具条 toolbar(employee_table) ()中是表格的过滤器的参数
        init_listen_table_toolbar() {
            table.on('toolbar(employee_table)', function (obj) {
                var checkStatus = table.checkStatus("employee_table_Id") //employee_table_Id来自layui 初始化表格ID
                    , choose_data = checkStatus.data; //获取选中的数据
                switch (obj.event) {
                    case 'add_employee':
                        employee.init_employee_form('add', undefined);
                        break;
                    case 'batch_employee_deleted':
                        employee.batch_delete_employee(choose_data);
                        break;
                    case 'assignment_employee_job':
                        employee.assignment_employee_job(choose_data);
                        break;
                }
            });
        },

        //打开新增/编辑弹框，这一层主要负责是否给编辑框赋值--->打开弹出层参数 type 类型 ,data 编辑改行的数据
        init_employee_form: function (type, data) {
            rowDataInfo = data;
            var form_title = '';
            type === 'add' ? form_title = "添加员工基本信息" : form_title = "编辑员工基本信息";
            $.get('/manage/form/edit_employee.html', function (html) {
                nowIndex = layer.open(  //弹出层
                    {
                        type: 1,
                        title: form_title,
                        area: ['900px', '450px'],
                        btnAlign: 'c',//按钮居中对齐
                        // content: $('#edit_employee_form'),
                        content: html,
                        anim: 5,//弹出效果 渐显
                        shift: -1,
                        btn: ['保存', '关闭'],
                        yes: function (index, layero) {
                            employee.update_form_employee(type, data);
                            return false;
                        },
                        btn2: function () {
                            jobCount =1;
                            removeEmployeeJob = { eId: '' , removeHdeIdJob :removeHdeIdJob=[]}; //清空 不处理的的员工职位信息
                            layer.close(nowIndex);
                        },
                        cancel: function(){
                            jobCount =1;
                            removeEmployeeJob = { eId: '' , removeHdeIdJob :removeHdeIdJob=[]}; //清空 不处理的的员工职位信息
                            layer.close(nowIndex);
                        },
                        success: function (layero,index) {
                            employeeDeletAndClearBtnListen(); //给编辑 职位tab的第一份职位绑定默认事件
                            removeEmployeeJob = { eId: '' , removeHdeIdJob :removeHdeIdJob=[]}; //清空 不处理的的员工职位信息
                            employee.listen_edit_button_click();
                            hospitalSelectInfo==undefined?getHttpHospitalSelectInfo():hospitalSelectInfo;
                            if (type === 'edit') {
                                let jobsCount = data.jobs.length;
                                //职位数量大于1份的要动态添加 职位表单
                                if (jobsCount>1){
                                    $.each(data.jobs, function (index, val) { //index是数组对象索引，val是对象
                                        if(index===0) {
                                            employee.init_employee_edit_hospital_dept_job(data, hospitalSelectInfo,index);
                                        }else {
                                            addNewJob();
                                            employee.init_employee_edit_hospital_dept_job(data,hospitalSelectInfo, index);
                                        }
                                    });
                                }else {
                                    //职位一份 或者一份一下的 不处理
                                    employee.init_employee_edit_hospital_dept_job(data,hospitalSelectInfo,0);
                                }
                                $("#employeeName").val(data.employeeName);
                                $("#employeeNumber").val(data.employeeNumber);
                                $("#phone").val(data.phone);
                                $("#mailbox").val(data.mailbox);
                                $("#identityCard").val(data.identityCard);
                                $("#employeeAddress").val(data.employeeAddress);
                                var form_type = data.sex;
                                form_type === 0 ? form_type = true : form_type = false;// 真*男 true : false
                                $('#rdoPartment').attr("checked", form_type);
                                $('#rdoRoom').attr("checked", !form_type);
                                var status = data.status;
                                status === 1 ? status = true :status = false;
                                $("#status").prop("checked",status);
                                $("#pDept_select").val(data.pdeptname);
                                $("#dept_select").val(data.departmentname);
                                employee.init_date_form(data.birthday);

                            }else {
                                employee.init_employee_add_hospital_dept_job(hospitalSelectInfo);
                                employee.init_date_form();
                            }
                            layero.addClass('layui-form');//添加form标识
                            layero.find('.layui-layer-btn0').attr('lay-filter','submit_employee').attr('lay-submit','');//将按钮弄成能提交的
                            form.render();
                        },
                    });
            })
        },

        // 初始化员工界面 表格上方的搜索条件
        initEmployeeTableSearch:function(){
            // 1、医院信息 下拉框
            alert(123)
            if (hospitalSelectInfo ==undefined){
                getHttpHospitalSelectInfo();
            }
            let documentId ;
            //第一份工作为默认 id ，第二份工作为 id2... id3...
            documentId = '#searchHospitalSelect';
            $.each(hospitalSelectInfo, function (index, val) { //index是数组对象索引，val是对象
                var hName = val.name + "(" + val.city + "/"+val.area+ ")";
                $(documentId).append(new Option(hName,val.id));
            });
            form.render('select');

            //2、部门树初始空下拉框
            this.init_dept_dtree([],'#searchDeptDtree')

        },

        /*
        *  监听 用户分配员工表格搜索提交、清除按钮
        */
        listenEmployeeSearchTableChooseAndClear:function(){
            //提交搜索
            alert(1234)
            $("#searchEmployeeBtn").click(function () {
                {
                    var searchEmployee = $("#searchEmployee").val();
                    var hId = $("#searchHospitalSelect").val();
                    layui.table.reload("employee_table_Id",{
                        where:{
                            searchEmployee: searchEmployee,
                            hId: hId,
                            deptChildId: dtree.getNowParam('searchDeptDtree').nodeId,
                        }
                    })
                }
            });
            //清除搜索
            $("#clearEmployeeBtn").click(function () {
                {
                    $("#searchEmployee").val('');
                    $("#searchHospitalSelect").val('');
                        dtree.reload( 'searchDeptDtree',{
                            data:  []
                        });
                    form.render('select');
                }
            });
        },

        /*
        * 监听员工表格上方 医院下拉框选择 联动部门显示
        */
        listenSearchEmployeeJobSelect:function( ){
            let documentDeptTreeId;
            //监听医院下拉选择
            form.on( 'select(searchHospitalSelect)', function(data){
                console.log(data.elem); //得到select原始DOM对象
                console.log(data.value); //得到被选中的值
                console.log(data.othis); //得到美化后的DOM对象
                let chooseElemIndex = 'searchDeptDtree';
                var hId =  data.value;
                let treeData;
                $.ajax({
                    url: "/manage/department/findDeptTreeList?isCheckArr=1&&isNotChoose=yes&&hospitalId="+  hId,
                    type: "GET",
                    success: function (resp) {
                        if (resp.code === 200) {
                            treeData = resp.data;
                            //重新加载渲染
                            dtree.reload( chooseElemIndex,{
                                data:  treeData,
                            });
                        }
                    }
                });
            });
        },

        // 初始化员工界面右侧eletree的部门树
        init_department_tree:function () {
            el= eleTree.render({
                elem: '.employeeTree',
                url: '/manage/hospital/hospAndDeptTree',
                showCheckbox: false,
                // contextmenuList: ['add','remove'],
                request: {
                    key: "permission_id",
                    name: "title",
                    children: "children",
                    checked: "checked",
                    disabled: "disabled",
                    isLeaf: "isLeaf"
                },
                response: {
                    statusName: "code",
                    statusCode: 200,
                    dataName: "data"
                }
            });
        },

        // 树节点点击事件
        choose_department_tree:function(){
            eleTree.on("nodeClick(employee_tree_data)",function(node) {
                var node_data = null;
                node_data =node.data.currentData;

                var type= null;
                var hId = null;
                var pid = null;
                var deptChildId =null;
                console.log(node_data);
                type= node_data.type;
                hId = node_data.hospitalId;
                if (type ==="hospital" ||type==="dept" || type === "childrenDept" ) {

                    //部门
                    if (type==="dept") {
                        type = null;
                        pid = node_data.deptId;
                        layui.table.reload("employee_table_Id",{
                            where:{
                                hId: hId,
                                type: type,
                                pId : pid,
                            }

                        })
                    }
                    //科室
                    else if (type === "childrenDept") {
                        type = 1;
                        pid = node_data.deptId;
                        deptChildId = node_data.deptChildId;
                        layui.table.reload("employee_table_Id",{
                            where:{
                                hId: hId,
                                type: type,
                                pId : pid,
                                deptChildId: deptChildId
                            }

                        })
                    }
                    //查该医院所有员工
                    else {
                        type = null;
                        layui.table.reload("employee_table_Id",{
                            where:{
                                hId: hId
                            }

                        })
                    }
                }

            });

        },

        init_dept_dtree:function(treeData,treeId){
            // 初始化树dtree renderSelect
            dtree.renderSelect({
                elem: treeId,
                data:  treeData,
            });
        },

        /*
        * 监听添加、编辑框员工 职位栏 医院下拉框选择 联动部门显示
         */
        listen_employee_job_select:function( ){
            let documentDeptTreeId;
            //监听医院下拉选择
            form.on( 'select(hospital_select)', function(data){
                console.log(data.elem); //得到select原始DOM对象
                console.log(data.value); //得到被选中的值
                console.log(data.othis); //得到美化后的DOM对象
                let chooseIndex = data.elem.id.charAt(data.elem.id.length-1);
                let chooseElemIndex = 'DeptDtree';
                switch (chooseIndex) {
                    case 't':  chooseElemIndex  ; break;
                    default: chooseElemIndex = chooseElemIndex + chooseIndex; break;
                }
                var hId =  data.value;
                let treeData;
                $.ajax({
                    url: "/manage/department/findDeptTreeList?isCheckArr=1&&isNotChoose=yes&&hospitalId="+  hId,
                    type: "GET",
                    success: function (resp) {
                        if (resp.code === 200) {
                            treeData = resp.data;
                            //重新加载渲染
                            dtree.reload( chooseElemIndex,{
                                data:  treeData,
                            });
                        }
                    }
                });
            });
        },

        /**
         * 编辑单个员工回显医院、部门、职业、职称
         * @param row 当前对象
         * @param hospitalInfo 医院下拉框信息
         * @param jobIndex 当前工作索引
         */
        init_employee_edit_hospital_dept_job: function(row,hospitalInfo,jobIndex){
            //动态更新医院信息
            let documentId ;
            //第一份工作为默认 id ，第二份工作为 id2... id3...
            if (jobIndex===0){
                documentId = '#hospital_select'
            }else {
                let strJobIndex = (jobIndex+1).toString();
                documentId = '#hospital_select' + strJobIndex ;

            }
            //动态给div元素添加 自定义元素
            let parentJobHtmlId = 'job'+ (jobIndex+1);
            let bindHtml = document.getElementById(parentJobHtmlId);
            if (bindHtml!=undefined){
                row==undefined? '':(row.jobs[jobIndex]==undefined?'':  bindHtml.setAttribute("data-hdeId", row.jobs[jobIndex].hdeId) );
                bindHtml.setAttribute('data-eId',row.employeeId);
            }
            $(documentId).empty();
            $(documentId).append(new Option("请选择","0"));
            $.each(hospitalInfo, function (index, val) { //index是数组对象索引，val是对象
                var hName = val.name + "(" + val.city + "/"+val.area+ ")";
                if (row!=undefined) {
                    let job = row.jobs[jobIndex];
                    let selectHospitalId = job==undefined?'':job.hospitalId;
                    if (selectHospitalId === val.id) {
                        $(documentId).append(new Option(hName,val.id,true,true));
                    }else {
                        $(documentId).append(new Option(hName,val.id));
                    }
                }else{
                    $(documentId).append(new Option(hName,val.id));
                }
            });

            // 2、回显每份职位的部门dtree树
            let treeData;
            let jobData = row.jobs[jobIndex];
            let hhId = jobData==undefined?'':jobData.hospitalId;
            $.ajax({
                url: "/manage/department/findDeptTreeList?isCheckArr=1&&isNotChoose=yes&&hospitalId="+  hhId,
                type: "GET",
                success: function (resp) {
                    if (resp.code === 200) {
                        treeData = resp.data;
                        let  documentDeptTreeId = 'DeptDtree';
                        // noinspection JSMismatchedCollectionQueryUpdate
                        var getDeTreeList =[deptTree1,deptTree2,deptTree3,deptTree4,deptTree5];
                        //第一份工作为默认 id ，第二份工作为 id2... id3...
                        //    documentDeptTreeId如果是 = '#DeptDtree'  js字符串截取要DeptDtree  运用方法substr documentDeptTreeId.substr(1)
                        if (jobIndex===0){
                            getDeTreeList[jobIndex] = dtree.renderSelect({
                                elem: '#'+documentDeptTreeId,
                                // width: "100%",
                                data:  treeData,
                                done: function(){
                                    dtree.dataInit(documentDeptTreeId ,  row.jobs[jobIndex].deptId );
                                    dtree.selectVal(documentDeptTreeId);
                                }
                            });
                        }else {
                            let strJobIndex = (jobIndex+1).toString();
                            documentDeptTreeId += strJobIndex ;
                            //重新加载渲染
                            getDeTreeList[jobIndex] = dtree.reload( documentDeptTreeId,{
                                data:  treeData,
                                done: function(){
                                    dtree.dataInit(documentDeptTreeId ,  row.jobs[jobIndex].deptId );
                                    dtree.selectVal(documentDeptTreeId);
                                }
                            });
                        }

                    }else {
                        layer.msg("获取员工部门信息失败");
                    }
                }
            });

            // 3、 4、回显处理职业和职位下拉框
            let nowJobId = row.jobs[jobIndex]==undefined?'' : row.jobs[jobIndex].jobId;
            let nowPJobId =  row.jobs[jobIndex]==undefined?'' : row.jobs[jobIndex].pjobId;
            let documentJobId,documentPJobId;
            //第一份工作为默认 id ，第二份工作为 id2... id3...
            if (jobIndex===0){
                documentPJobId = '#pJob_select';
                documentJobId = '#job_select';
            }else {
                let strJobIndex = (jobIndex+1).toString();
                documentPJobId = '#pJob_select' + strJobIndex ;
                documentJobId = '#job_select' + strJobIndex ;
            }
            //获取http职业和职位
            jobSelectInfo==undefined?getHttpJobSelectInfo():jobSelectInfo;
            $(documentPJobId).empty();
            $.each(jobSelectInfo, function (index, val) { //index是数组对象索引，val是对象
                if (index===0){
                    $(documentPJobId).append(new Option("请选择","0"));
                }
                if (nowPJobId!=undefined){
                    if (val.type===0){
                        if (val.jobId === nowPJobId){
                            $(documentPJobId).append(new Option(val.jobName,val.jobId,true,true));
                        }else {
                            $(documentPJobId).append(new Option(val.jobName,val.jobId));
                        }
                    }else if (val.type===1) {
                        //可是下拉框
                        if (val.jobId === nowJobId && val.parentId === nowPJobId){
                            $(documentJobId).append(new Option(val.jobName,val.jobId,true,true));
                        }else if (val.parentId === nowPJobId){
                            $(documentJobId).append(new Option(val.jobName,val.jobId));
                        }
                    }
                } else {
                    if (val.type===0){
                        $(documentPJobId).append(new Option(val.jobName,val.jobId));
                    }
                }
            });
            form.render('select')
        },

        /**
         * 初始化 员工医院和职业的回显
         * @param hospitalInfo 医院下拉框信息
         */
        init_employee_add_hospital_dept_job: function(hospitalInfo){
            // 1、填充医院下拉框信息
            let documentId ='#hospital_select';

            $(documentId).empty();
            $(documentId).append(new Option("请选择","0"),true,true);
            $.each(hospitalInfo, function (index, val) { //index是数组对象索引，val是对象
                var hName = val.name + "(" + val.city + "/"+val.area+ ")";
                $(documentId).append(new Option(hName,val.id));
            });

            // 2、填充 部门空选框
            let emptyData= [];
            employee.init_dept_dtree(emptyData,  '#DeptDtree');

            // 3、和4、填充 职业下拉框
            let  documentPJobId = '#pJob_select';
            let  documentJobId = '#job_select';
            //获取http职业和职位
            // noinspection EqualityComparisonWithCoercionJS
            jobSelectInfo==undefined?getHttpJobSelectInfo():jobSelectInfo;
            $.each(jobSelectInfo, function (index, val) { //index是数组对象索引，val是对象
                if (val.type===0){
                    $(documentPJobId).append(new Option(val.jobName,val.jobId));
                }
            });
            form.render('select')
        },

        //编辑 点击保存按钮后提交处理
        update_form_employee: function (type, data) {
            let hospitalSelectId = '#hospital_select';
            let DeptDtreeId = 'DeptDtree';
            let pJob_select = '#pJob_select';
            let job_select = '#job_select';
            // 员工表单信息校验
            //校验手机号
            let submitMobile= $("#phone").val();
            let submitEmail= $("#mailbox").val();
            let submitIdentityCard= $("#identityCard").val();
            if (submitMobile===''){
                layer.msg( "手机号不能为空，请输入手机号！", {icon: 5});
                return;
            }else {
                if (!checkMobile(submitMobile)){
                    layer.msg( "请输入规范的手机号！", {icon: 5});
                    return;
                }
            }
            //校验邮箱号
            if (submitEmail!==''){
                if (!checkEmail(submitEmail)){
                    layer.msg( "请输入规范的邮箱号！", {icon: 5});
                    return;
                }
            }
            //校验身份证号
            // if (submitIdentityCard!==''){
            //     if (!checkIdentityCard(submitIdentityCard)){
            //         layer.msg( "请输入规范的身份证号！", {icon: 5});
            //         return;
            //     }
            // }

            // 请求方式处理和URL处理
            if (type === 'add') {
                request_method = 'POST';
                request_url = '/manage/employee';
            } else {
                request_method = 'PUT';
                request_url = '/manage/employee/' + data.employeeId;
            }
            var status = $("#status").prop("checked");
            status ? status = 1 : status = 0;

            let jobs= []; //批量定义
            for(var j=0;j<6;j++){
                let varName='job'+ (j+1);  //动态定义变量名
                if (j===0){
                    if ( $( hospitalSelectId  ).val() === undefined ){
                        continue;
                    }else {
                         varName= {
                            hdeId:  data==undefined?'':(data.jobs[j]==undefined?'': data.jobs[j].hdeId),
                            hospitalId:  $( hospitalSelectId  ).val(),
                            deptId:  dtree.getNowParam( DeptDtreeId ).nodeId,
                            pJobId: $( pJob_select ).val(),
                            jobId: $( job_select).val(),
                        };
                    }
                    jobs.push(varName);
                }else {
                    if ( $( hospitalSelectId + ( (j+1).toString())  ).val() === undefined ){
                        continue;
                    }else {
                        varName = {
                            hdeId: data==undefined?'':(data.jobs[j]==undefined?'': data.jobs[j].hdeId),
                            hospitalId:  $( hospitalSelectId + ( (j+1).toString()) ).val(),
                            deptId:  dtree.getNowParam( DeptDtreeId + ((j+1).toString())).nodeId,
                            pJobId: $( pJob_select + ( (j+1).toString() ) ).val(),
                            jobId: $( job_select + ( (j+1).toString() ) ).val(),
                        };
                    }
                    jobs.push(varName);
                }
            }
            let deleteHdeIds;
            if (data !=undefined &&(removeEmployeeJob.eId===data.employeeId)){
                deleteHdeIds = removeEmployeeJob.removeHdeIdJob;
            }
            let employee_form_data = {
                employeeName: $("#employeeName").val(),
                employeeNumber: $("#employeeNumber").val(),
                phone: submitMobile,
                mailbox: submitEmail,
                identityCard: submitIdentityCard,
                employeeAddress: $("#employeeAddress").val(),
                sex: $('input[name="sex"]:checked').val(),
                birthday:  birthday_date,
                status: status,
                jobs : jobs,
                deleteHdeIds : deleteHdeIds
            };

            $.ajax({
                url: request_url,
                contentType: "application/json",
                type: request_method,
                data: JSON.stringify(employee_form_data ),
                success: function (resp) {
                    if (resp.code === 200) {
                        var data = resp.data;
                        layer.msg('保存成功', {icon: 1});
                        layer.close(nowIndex);
                        employee_table_Info.reload();
                    } else {
                        layui.form.render();
                        let errorMsg;
                        resp.msg==undefined?errorMsg="保存失败": errorMsg="保存失败,"+resp.msg;
                        layer.msg( errorMsg, {icon: 5});
                    }
                    jobCount =1;
                }
            });


        },

        //员工单行删除
        delete_employee: function (data) {
            layer.confirm("是否删除[" + data.employeeName + "]", function (index) {
                $.ajax({
                    type: "DELETE",
                    contentType: "application/json",//设置请求参数类型为json字符串
                    url: "/manage/employee/" + data.employeeId,
                    success: function (resp) {
                        var code = resp.code;
                        if (code === 200) {
                            layer.msg('删除成功', {icon: 1});
                            employee_table_Info.reload();
                        } else {
                            layer.msg("删除失败 " + resp.msg, {icon: 5});
                        }
                    }
                });
                layer.close(index);
                //向服务端发送删除指令
            });
        },

        //员工批量删除 choose_data选中的行数据
        batch_delete_employee: function (choose_data) {
            if (choose_data.length === 0) {
                layer.msg('请选择一行');
            } else {
                var keyArr = '';
                var nameArr = '';
                $.each(choose_data, function (index, val) { //index是数组对象索引，val是对象
                    if (index === 0) {
                        keyArr = keyArr + val.employeeId;
                        nameArr = nameArr + val.employeeName;
                    } else {
                        keyArr = keyArr + ',' + val.employeeId;
                        nameArr = nameArr + ',' + val.employeeName;
                    }
                });

                layer.confirm('是否确定删除选中的数据[' + nameArr + "]",
                    {
                        icon: 0,
                        title: "提示",
                        skin: "deleteTips"
                    }
                    , function () {
                        $.ajax({
                            type: "POST",
                            contentType: "application/x-www-form-urlencoded",//设置请求参数类型为json字符串
                            url: "/manage/employee/batchDelete",
                            data: {
                                ids: keyArr,
                                nameArr: nameArr
                            },
                            success: function (resp) {
                                var code = resp.code;
                                if (code === 200) {
                                    layer.msg('删除成功', {icon: 1});
                                    employee_table_Info.reload();
                                } else {
                                    layer.msg("删除失败", {icon: 5});
                                }
                            }
                        });


                    });
            }
        },

        //时间工具组件
        init_date_form:function(value){
           laydate.render({
                elem: '#birthday' ,//指定元素
                trigger: 'click'
                ,theme: '#616261'
                ,value : value  //用于编辑回显给表单赋初值
                ,done: function(value, date, endDate){
                    // 编辑/添加选取过时间值，存放在变量birthday_date中
                    birthday_date = value;
                }
            });
        },

        // 表格页面监听表单中的switch改变发送请求
        listen_employee_table_switch: function() {
            //监听行单击事件
            form.on('switch(employee_table_Switch)', function(data){
                var switch_status = data.elem.checked?1:0;
                var row_data = JSON.parse( data.elem.getAttribute('row-data'));
                $.ajax({
                    url: "/manage/employee/" + row_data.employeeId,
                    contentType : "application/json",
                    type: 'PUT',
                    data:JSON.stringify( {status:switch_status}),
                    success: function (resp) {
                        if (resp.code===200){
                            var data = resp.data;
                            layer.msg('保存成功', {icon: 1});
                            employee_table_Info.reload();
                        }else {
                            layui.form.render();
                            layer.msg("保存失败"+ " "+ resp.msg, {icon: 5});
                        }

                    }
                });

            });



        },

        assignment_employee_job:function(data){
            $.get('/manager/employeeForm', function (html) {
                nowIndex = layer.open(  //弹出层
                    {
                        type: 1,
                        title: "分配员工职位",
                        area: ['750px', '450px'],
                        btnAlign: 'c',//按钮居中对齐
                        content: html,
                        anim: 5,//弹出效果 渐显
                        shift: -1,
                        btn: ['保存', '关闭'],
                        yes: function (index, layero) {
                            form.on('submit(submit_employee)',function(){

                                return false;
                            });


                        },
                        btn2: function () {
                        },
                        success: function (layero,index) {


                        },

                    });
            })
        },

        /*
        *监听编辑工作职位页面的按钮点击事件
         */
        listen_edit_button_click(){
            $("#addNewJobButton").click(function () {
                console.log("增加新的一行");
                if (jobCount<5){
                    addNewJob();//增加一条内容函数
                    form.render();//每次点击添加按钮就会重新渲染一次
                }else {
                    layer.msg("最大只能拥有5份不同的职位！", {icon: 5});
                }
            });

            $(".deleteNewJobButton").click(function () {
                console.log("删除一行");

            });


            form.on('select(pJob_select)', function(data){
                console.log(data.elem); //得到select原始DOM对象
                console.log(data.value); //得到被选中的值
                console.log(data.othis); //得到美化后的DOM对象
                let chooseIndex = data.elem.id.charAt(data.elem.id.length-1);
                let chooseElemIndex = '#job_select';
                switch (chooseIndex) {
                    case 't':  chooseElemIndex  ; break;
                    default: chooseElemIndex = chooseElemIndex + chooseIndex; break;
                    // case '2':  chooseElemIndex = chooseElemIndex + chooseIndex; break;
                    // case '3':  chooseElemIndex = chooseElemIndex + chooseIndex; break;
                    // case '4':  chooseElemIndex = chooseElemIndex + chooseIndex;break;
                    // case '5':  chooseElemIndex = chooseElemIndex + chooseIndex; break;
                }

                //获取职业和职位
                $.ajax({
                    url:  '/manage/job',
                    type: 'GET',
                    data : {
                       'type': "1",
                        'pId': data.value
                    },
                    success: function (resp) {
                        if (resp.code === 200) {
                            var data = resp.data;
                            jobData = data;

                            $(chooseElemIndex).empty();
                            $.each(data, function (index, val) { //index是数组对象索引，val是对象
                                //下拉框
                                $(chooseElemIndex).append(new Option(val.jobName,val.jobId));
                            });
                            form.render('select')
                        } else {
                            layer.msg("获取职称信息失败！");
                        }

                    }
                });
            });
        },

        init_listen_dtree_click:function(){
            // 绑定节点点击
            dtree.on("node('demoTree')" ,function(obj){
                var chearr = dtree.getCheckbarNodesParam("demoTree");
                console.log(chearr);
                layer.msg(JSON.stringify(obj.param));
            });
        },

    };

// ----------------------------------
    /*
    * 员工编辑 职位信息 动态添加多职位
    */
    function addNewJob() {
        jobCount += 1;
        let newJob=
            '   <div  id="job'+jobCount+'"  >\n' +
            '           <hr>职位'+jobCount+'：\n' +
            '                    <div  style="text-align:right">\n' +
            '                        <button id="deleteNewJobButton'+ jobCount +'" type="button" class="layui-btn layui-btn-primary layui-btn-sm " ' +
            '                                    lay-event="delete_empJob'+ jobCount +'"  >\n' +
            '                            <i class="layui-icon">&#xe640;</i>\n' +
            '                        </button>\n' +
            '                        <button id="resetJob'+jobCount+'" class="layui-btn layui-btn-primary layui-btn-sm">\n' +
            '                            <i class="layui-icon">&#xe669;</i>\n' +
            '                        </button>'+
            '                    </div>' +
            '                    <div class="layui-form-item">\n' +
            '                        <label class="layui-form-label">医院</label>\n' +
            '                        <div class="layui-input-inline">\n' +
            '                            <select   id = "hospital_select'+jobCount+'"  lay-filter="hospital_select">\n' +
            '                                <option value="0">请选择</option>\n' +
            '                            </select>\n' +
            '                        </div>\n' +
            '                        <label class="layui-form-label">部门</label>\n' +
            '                        <div class="layui-input-inline">\n' +
            '                            <ul id="DeptDtree'+jobCount+'" class="dtree" data-id="0"></ul>\n' +
            '                        </div>\n' +
            '                    </div>\n' +
            '                    <div class="layui-form-item">\n' +
            '\n' +
            '\n' +
            '                        <label class="layui-form-label">职业</label>\n' +
            '                        <div class="layui-input-inline">\n' +
            '                            <select   id = "pJob_select'+jobCount+'" lay-filter="pJob_select">\n' +
            '                                <option value="0">请选择</option>\n' +
            '                            </select>\n' +
            '                        </div>\n' +
            '\n' +
            '                        <label class="layui-form-label">职称</label>\n' +
            '                        <div class="layui-input-inline">\n' +
            '                            <select   id = "job_select'+jobCount+'" lay-filter="job_select">\n' +
            '                                <option value="0">请选择</option>\n' +
            '                            </select>\n' +
            '                        </div>\n' +
            '\n' +
            '                    </div>\n' +
            '                </div>';

        $('#job_form_parent').append(newJob);
        //追加编辑中新增的医院信息
        if (hospitalSelectInfo ==undefined){
            getHttpHospitalSelectInfo();
        }
        let documentId ;
        //第一份工作为默认 id ，第二份工作为 id2... id3...
        documentId = '#hospital_select' +  jobCount.toString();
        $.each(hospitalSelectInfo, function (index, val) { //index是数组对象索引，val是对象
            var hName = val.name + "(" + val.city + "/"+val.area+ ")";
            $(documentId).append(new Option(hName,val.id));
        });
        form.render('select');

        //获取职业和职位
        let emptyData= [];
        employee.init_dept_dtree(emptyData,  '#DeptDtree' +jobCount);

        let nowJobId =  '#job_select'+ jobCount.toString();
        let nowPJobId = '#pJob_select' + jobCount.toString();
        jobSelectInfo==undefined?getHttpJobSelectInfo():jobSelectInfo;
        $.each(jobSelectInfo, function (index, val) { //index是数组对象索引，val是对象
            if (val.type===0){
                $(nowPJobId).append(new Option(val.jobName,val.jobId));
            }
        });
        //给每个 新的工作添加 删除按钮功能
        document.getElementById('deleteNewJobButton'+ jobCount ).addEventListener('click', function(){
            console.log(event.currentTarget);
            let removeCount =   event.currentTarget.id.substr(-1);
            let removeId = 'job'+removeCount;
            let nowJobHtmlDiv = document.getElementById(removeId );
            if (nowJobHtmlDiv != null){
                // nowJobHtmlDiv.parentNode.removeChild(nowJobHtmlDiv);
                let hdeId = nowJobHtmlDiv.getAttribute('data-hdeId');
                let eId = nowJobHtmlDiv.getAttribute('data-eId');
                console.log("remove hdeId is : "+  hdeId);
                removeEmployeeJob['eId']  = eId;
                removeEmployeeJob.removeHdeIdJob.push(hdeId);
                console.log(removeEmployeeJob);
                nowJobHtmlDiv.remove();
            }
        });
        //给每个 新的工作添加  清除按钮功能
        document.getElementById('resetJob'+ jobCount ).addEventListener('click', function(){
            let removeCount =   event.currentTarget.id.substr(-1);
            let removeId = 'job'+removeCount;
            let nowJobHtmlDiv = document.getElementById(removeId );
            if (nowJobHtmlDiv != null){
                $('#hospital_select' +  removeCount.toString()).val("0"); // 1、医院恢复默认
                dtree.reload( 'DeptDtree' +removeCount,{data:  [],});     // 2、部门恢复默认清空
                $('#pJob_select' +  removeCount.toString()).val("0"); // 3、职业恢复默认
                $('#job_select' +  removeCount.toString()).empty(); // 4、职位恢复默认清空
                form.render('select');
            }
        });
        form.render('select');
    }

    /**
     * 绑定员工编辑框中的第一份工作的删除和清除按钮逻辑
     */
    function employeeDeletAndClearBtnListen( ) {
        //给每个 新的工作添加 删除按钮功能：把删除hdeId添加到容器中 清空第一份工作的信息
        document.getElementById('deleteNewJobButton1' ).addEventListener('click', function(){
            console.log(event.currentTarget);
            let removeCount =   event.currentTarget.id.substr(-1);
            let removeId = 'job'+removeCount;
            let nowJobHtmlDiv = document.getElementById(removeId);
            if (nowJobHtmlDiv != null){
                // nowJobHtmlDiv.parentNode.removeChild(nowJobHtmlDiv);
                let hdeId = nowJobHtmlDiv.getAttribute('data-hdeId');
                let eId = nowJobHtmlDiv.getAttribute('data-eId');
                console.log("remove hdeId is : "+  hdeId);
                removeEmployeeJob['eId']  = eId;
                removeEmployeeJob.removeHdeIdJob.push(hdeId);
                //同时清空 下拉框
                $('#hospital_select').val("0"); // 1、医院恢复默认
                dtree.reload( 'DeptDtree' ,{data:  [],});     // 2、部门恢复默认清空
                $('#pJob_select').val("0"); // 3、职业恢复默认
                $('#job_select').empty(); // 4、职位恢复默认清空
                console.log(removeEmployeeJob);
                form.render('select');
            }
        });
        //给每个 新的工作添加  清除按钮功能 ：清空下拉框内容
        document.getElementById('resetJob1' ).addEventListener('click', function(){
            let removeCount =   event.currentTarget.id;
            let nowJobHtmlDiv = document.getElementById(removeCount);
            if (nowJobHtmlDiv != null){
                $('#hospital_select').val("0"); // 1、医院恢复默认
                dtree.reload( 'DeptDtree' ,{data:  [],});     // 2、部门恢复默认清空
                $('#pJob_select').val("0"); // 3、职业恢复默认
                $('#job_select').empty(); // 4、职位恢复默认清空
                form.render('select');
            }
        });
    }

    /*
    * 获取医院信息下拉框
    */
    function getHttpHospitalSelectInfo() {
        $.ajax({
            url:  '/manage/hospital',
            type: 'GET',
            async : false,
            success: function (resp) {
                if (resp.code === 200) {
                    hospitalSelectInfo =  resp.data;
                } else {
                    layer.msg("获取医院信息失败");
                }

            }
        });
    }

    /*
    * 获取职位信息下拉框
     */
    function getHttpJobSelectInfo() {
        $.ajax({
            url:  '/manage/job',
            type: 'GET',
            async : false,
            success: function (resp) {
                if (resp.code === 200) {
                    jobSelectInfo =  resp.data;
                } else {
                    layer.msg("获取职业信息失败！");
                }

            }
        });
    }


    /**
     * 校验手机号
     */
    function checkMobile( strMobile ) {
        //13588888888
        let strRegExp = /^[1][345678][0-9]{9}$/;
        let re = new RegExp(strRegExp);
        return re.test(strMobile);
    }

    /**
     * 校验邮箱
     */
    function checkEmail( strEmail ) {
        let strRegExp = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        let re = new RegExp(strRegExp);
        return re.test(strEmail);
    }

    /**
     * 校验身份证号
     */
    function checkIdentityCard( idcode ) {
        // 加权因子
        var weight_factor = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
        // 校验码
        var check_code = ['1', '0', 'X' , '9', '8', '7', '6', '5', '4', '3', '2'];

        var code = idcode + "";
        var last = idcode[17];//最后一位

        var seventeen = code.substring(0,17);

        // ISO 7064:1983.MOD 11-2
        // 判断最后一位校验码是否正确
        var arr = seventeen.split("");
        var len = arr.length;
        var num = 0;
        for(var i = 0; i < len; i++){
            num = num + arr[i] * weight_factor[i];
        }

        // 获取余数
        var resisue = num%11;
        var last_no = check_code[resisue];

        // 格式的正则
        // 正则思路 111111 19961121 0123
        /*
        第一位不可能是0
        第二位到第六位可以是0-9
        第七位到第十位是年份，所以七八位为19或者20
        十一位和十二位是月份，这两位是01-12之间的数值
        十三位和十四位是日期，是从01-31之间的数值
        十五，十六，十七都是数字0-9
        十八位可能是数字0-9，也可能是X
        */
        var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;

        // 判断格式是否正确
        var format = idcard_patter.test(idcode);

        // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
        return last === last_no && format ? true : false;
    }


    employee.init_listen_dtree_click();
    employee.init_employee_table();
    employee.init_department_tree();
    employee.init_date_form();
    employee.choose_department_tree();
    employee.listen_employee_table_switch();
    employee.init_listen_table_tool();
    employee.init_listen_table_toolbar();
    employee.listen_employee_job_select();
    employee.initEmployee();
    exports("employee", employee);


});